<template>
    <a-form ref="formRef" :model="formData" :rules="formRules" auto-label-width>
        <template
            v-if="type === DATA_TYPE.INTEGER || type === DATA_TYPE.DECIMAL"
        >
            <a-row :gutter="16">
                <a-col :span="12">
                    <a-form-item field="min" :label="$t('zui-xiao-zhi')">
                        <a-input-number
                            v-model="formData.min"
                            :precision="type === DATA_TYPE.DECIMAL ? 2 : 0"
                            :placeholder="$t('qing-shu-ru-zui-xiao-zhi')"
                            model-event="input"
                        />
                    </a-form-item>
                </a-col>
                <a-col :span="12">
                    <a-form-item field="max" :label="$t('zui-da-zhi')">
                        <a-input-number
                            v-model="formData.max"
                            :precision="type === DATA_TYPE.DECIMAL ? 2 : 0"
                            :placeholder="$t('qing-shu-ru-zui-da-zhi')"
                            model-event="input"
                        />
                    </a-form-item>
                </a-col>
                <a-col :span="12">
                    <a-form-item field="unit" :label="$t('dan-wei')">
                        <a-input
                            v-model="formData.unit"
                            :placeholder="$t('qing-shu-ru-dan-wei')"
                        />
                    </a-form-item>
                </a-col>
                <a-col :span="12">
                    <a-form-item
                        field="unitName"
                        :label="$t('dan-wei-ming-cheng')"
                    >
                        <a-input
                            v-model="formData.unitName"
                            :placeholder="$t('qing-shu-ru-dan-wei')"
                        />
                    </a-form-item>
                </a-col>
            </a-row>
        </template>
        <template v-else-if="type === DATA_TYPE.ENUM">
            <a-form-item
                v-for="(item, index) in formDataList"
                :key="item.key"
                :merge-props="false"
                class="items-start"
                hide-label
            >
                <a-form-item
                    :field="`[${index}]`"
                    :label="$t('mei-ju-zhi')"
                    :rules="[
                        {
                            required: true,
                            validator: getEnumValidator(
                                item.data,
                                'key',
                                '请输入枚举值'
                            ),
                        },
                    ]"
                >
                    <a-input
                        v-model="item.data.key"
                        :placeholder="$t('mei-ju-zhi-0')"
                    ></a-input>
                </a-form-item>
                <a-form-item
                    :field="`[${index}].value`"
                    :labe="枚举说明"
                    :rules="[
                        {
                            required: true,
                            validator: getEnumValidator(
                                item.data,
                                'value',
                                '请输入枚举说明'
                            ),
                        },
                    ]"
                >
                    <a-input
                        v-model="item.data.value"
                        :placeholder="$t('mei-ju-shuo-ming')"
                    ></a-input>
                </a-form-item>
                <a-button :style="{ marginLeft: '10px' }" @click="handleAdd">{{
                    $t('zeng-jia')
                }}</a-button>
                <a-button
                    :style="{ marginLeft: '10px' }"
                    @click="handleDelete(index)"
                    >{{ $t('delete') }}</a-button
                >
            </a-form-item>
        </template>
        <template v-else-if="type === DATA_TYPE.BOOLEAN">
            <a-row :gutter="16">
                <a-col :span="12">
                    <a-form-item field="0" label="0">
                        <a-input
                            v-model="formData['0']"
                            :placeholder="$t('qing-shu-ru-0-de-zhi')"
                        />
                    </a-form-item>
                </a-col>
                <a-col :span="12">
                    <a-form-item field="1" label="1">
                        <a-input
                            v-model="formData['1']"
                            :precision="0"
                            :placeholder="$t('qing-shu-ru-1-de-zhi')"
                        />
                    </a-form-item>
                </a-col>
            </a-row>
        </template>
    </a-form>
</template>

<script lang="ts" setup>
    import { PropType, ref, computed, watch } from 'vue';
    import { useI18n } from 'vue-i18n';
    import { DATA_TYPE } from './const';

    const { t } = useI18n();

    function generateUUID() {
        let uuid = '';
        const hexDigits = '0123456789abcdef';
        for (let i = 0; i < 36; i += 1) {
            if (i === 8 || i === 13 || i === 18 || i === 23) {
                uuid += '-';
            } else if (i === 14) {
                uuid += '4';
            } else {
                uuid += hexDigits[Math.floor(Math.random() * 16)];
            }
        }
        return uuid;
    }

    const props = defineProps({
        modelValue: {
            type: Object as PropType<any>,
            default: () => ({}),
        },
        type: {
            type: String,
            default: DATA_TYPE.INTEGER,
        },
    });
    const formRef = ref();
    const formData = computed(() => props.modelValue);
    const formRules = {
        min: [
            { required: true, message: t('qing-shu-ru-zui-xiao-zhi') },
            {
                validator(value: number, cb: any) {
                    if (value > formData.value.max) {
                        cb(t('zui-xiao-zhi-bu-neng-da-yu-zui-da-zhi'));
                    } else {
                        cb();
                    }
                },
            },
        ],
        max: [
            { required: true, message: t('qing-shu-ru-zui-da-zhi') },
            {
                validator(value: number, cb: any) {
                    if (value < formData.value.min) {
                        cb(t('zui-da-zhi-bu-neng-xiao-yu-zui-xiao-zhi'));
                    } else {
                        cb();
                    }
                },
            },
        ],
        unit: [{ required: true, message: t('qing-shu-ru-dan-wei') }],
        unitName: [
            {
                required: true,
                message: t('qing-shu-ru-dan-wei-ming-cheng'),
            },
        ],
    };

    const formDataList = ref<
        {
            key: string;
            data: { key: string; value: string };
        }[]
    >([]);

    const nodeKeys = new Map<any, string>();
    function getEnumValidator(data: any, key: string, message: string) {
        return (_value: any, cb: any) => {
            const value = data[key];
            if (!value) {
                cb(message);
            } else if (value && key === 'key') {
                const len = formDataList.value.filter(
                    (item) => item.data.key === value
                ).length;
                if (len > 1) {
                    cb(t('mei-ju-zhi-bu-neng-zhong-fu'));
                } else {
                    cb();
                }
            } else {
                cb();
            }
        };
    }

    function init() {
        formDataList.value = props.modelValue.map((item: any) => {
            const key = nodeKeys.get(item) || generateUUID();
            nodeKeys.set(t, key);
            return {
                key,
                data: item,
            };
        });
    }

    watch(
        () => props.modelValue,
        () => {
            if (props.type === DATA_TYPE.ENUM) {
                init();
            }
        },
        { immediate: true }
    );

    function handleAdd() {
        formData.value.push({
            key: '',
            value: '',
        });
        init();
    }

    function handleDelete(index: number) {
        formData.value.splice(index, 1);
        init();
    }

    function validate() {
        return formRef.value.validate();
    }

    function resetFields() {
        formRef.value.resetFields();
    }

    defineExpose({
        validate,
        resetFields,
    });
</script>

<style lang="less" scoped>
    .items-start {
        :deep(.arco-form-item-content) {
            align-items: flex-start;
        }
    }
</style>
